package ru.spbau.lifeincube.swing;

import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.geometry.Point3D;
import javafx.util.Duration;
import ru.spbau.lifeincube.gui3d.Cube;
import ru.spbau.lifeincube.gui3d.interpolator.SpringInterpolator;
import ru.spbau.lifeincube.math.Vector3D;

public class LifeAnimation {
	private Point3D origin;

	public LifeAnimation() {
		this(new Point3D(0,0,0));
	}

	public LifeAnimation(Point3D origin) {
		this.origin = origin;
	}

	public Timeline getAnimation(Cube cube, Point3D cubeCenter, Point3D coord) {

		Vector3D direction = substract(cubeCenter, origin);
		double amplitude = 0.9*direction.length();
		direction.normalize();

		Timeline timeline = new Timeline();
		timeline.getKeyFrames().addAll(
				new KeyFrame(Duration.ZERO,
						new KeyValue(cube.translateXProperty(), cubeCenter.getX()),
						new KeyValue(cube.translateYProperty(), cubeCenter.getY()),
						new KeyValue(cube.translateZProperty(), cubeCenter.getZ())
				),
				new KeyFrame(Duration.seconds(2),
						new KeyValue(
								cube.translateXProperty(),
								cubeCenter.getX() + amplitude * direction.getX(),
								new SpringInterpolator()
						),
						new KeyValue(
								cube.translateYProperty(),
								cubeCenter.getY() + amplitude * direction.getY(),
								new SpringInterpolator()
						),
						new KeyValue(
								cube.translateZProperty(),
								cubeCenter.getZ() + amplitude * direction.getZ(),
								new SpringInterpolator()
						)
				)
		);

		timeline.setAutoReverse(true);
		timeline.setCycleCount(Timeline.INDEFINITE);
		return timeline;
	}

	private Vector3D substract(Point3D p1, Point3D p2) {
		return new Vector3D(new Point3D(p1.getX() - p2.getX(), p1.getY() - p2.getY(), p1.getZ() - p2.getZ()));
	}
}
